<template>
  <div class="scroll-container">
    <h2>{{ title }}</h2>
    <a-button type="primary" @click="toImageFilesTablePage">
      查看&nbsp;{{this.$route.query.experiment_name}}&nbsp;实验下其他文件
    </a-button>
    <a-divider
      type="horizontal"
      :style="{ borderColor: '#19a7ff', borderWidth: '2px' }"
    />

    <a-spin :spinning="loading">
      <a-table :columns="imageTableColumns" :data-source="Data" :pagination="false" :scroll="{ y: '70vh' }">
        <template #bodyCell="{ column, record }">
          <template v-if="column.key === 'action'">
            <span>
              <a-button 
                :loading="record.processing" 
                @click="handleClickPic(record)"
              >
                {{ record.processing ? '处理中...' : '查看' }}
              </a-button>
              <a-divider type="vertical" />
            </span>
          </template>
        </template>
      </a-table>
    </a-spin>
  </div>
</template>

<script>
import { defineComponent } from 'vue';
import axiosInstance from "@/axios/axios.js";
import TIFF from 'tiff.js';
import { message } from 'ant-design-vue';

export default defineComponent({
  name: "MyDataImage",
  data() {
    return {
      loading: false,
      title: '图片列表',
      Data: [],
      imageTableColumns: [
        {
          title: "文件名",
          dataIndex: "name",
          key: "name"
        },
        {
          title: "操作",
          key: "action",
          scopedSlots: { customRender: "action" }
        }
      ]
    };
  },
  async created() {
    // 检查登录状态
    if (!this.$cookies.get('jwt') || !sessionStorage.getItem("isLogin")) {
      message.warning('请先登录');
      this.$router.push('/login');
      return;
    }

    // 检查路由参数
    const requiredParams = [
      'experiment_id',
      'experiment_set_name',
      'experiment_batch_name',
      'experiment_name'
    ];
    const missingParams = requiredParams.filter(param => !this.$route.query[param]);
    if (missingParams.length > 0) {
      message.error('缺少必要的参数');
      this.$router.push('/MyData');
      return;
    }

    // 检查用户信息
    const username = this.$cookies.get("username");
    
    if (!username) {
      message.error('用户信息不完整，请重新登录');
      this.$router.push('/login');
      return;
    }

    // 设置标题
    this.title = `图片列表 - ${this.$route.query.experiment_name}`;

    await this.initImageData();
  },
  methods: {
    async initImageData() {
      this.loading = true;
      try {
        const response = await axiosInstance({
          method: "POST",
          url: "/myData/getImages",
          headers: {
            Authorization: `Bearer ${this.$cookies.get("jwt")}`
          },
          data: {
            username: this.$cookies.get("username"),
            dataId: this.$route.query.experiment_id,
            experimentSetName: this.$route.query.experiment_set_name,
            batchName: this.$route.query.experiment_batch_name,
            experimentName: this.$route.query.experiment_name,
          },
        });

        if (response.data?.data?.images && response.data.data.url) {
          const imagesPath = response.data.data.url;
          console.log('Response from server:', response.data);
          if (response.data?.data?.images && response.data.data.url) {
            const imagesPath = response.data.data.url;
            this.Data = response.data.data.images.map(item => {
              console.log('Processing image item:', item);
              // 确保字段名称与后端返回的一致
              const processedItem = {
                ...item,
                imgUrl: imagesPath + item.name,
                processing: false,
                // 使用后端返回的原始字段名
                width: item.width,
                height: item.height,
                file_size: item.file_size,
                mime_type: item.mime_type,
                created_at: item.created_at,
                file_hash: item.file_hash,
                metadata: item.metadata
              };
              console.log('Processed image item:', processedItem);
              return processedItem;
            });
          }
        } else {
          console.warn("No images data in response:", response.data);
          this.Data = [];
        }
      } catch (error) {
        console.error('获取图片数据失败:', error);
        if (error.response?.status === 401) {
          message.error('登录已过期，请重新登录');
          this.$router.push('/login');
        } else {
          message.error(`获取数据失败: ${error.response?.data?.message || error.message}`);
        }
      } finally {
        this.loading = false;
      }
    },

    async handleClickPic(image) {
      // 更新图片状态
      const index = this.Data.findIndex(img => img.name === image.name);
      if (index !== -1) {
        this.Data[index].processing = true;
      }

      try {
        if (!image.experiment_set_id || !image.batch_id || !image.experiment_id || !image.tx_hash) {
          throw new Error('图片信息不完整');
        }

        let base64data;
        if (image.imgUrl.endsWith('.tif')) {
          // 处理 TIFF 文件
          const response = await fetch(image.imgUrl);
          if (!response.ok) {
            throw new Error(`Failed to load TIF image: ${response.statusText}`);
          }

          const buffer = await response.arrayBuffer();
          const tiff = new Tiff({ buffer });
          const canvas = document.createElement('canvas');
          const ctx = canvas.getContext('2d');
          const width = tiff.width();
          const height = tiff.height();
          canvas.width = width;
          canvas.height = height;
          const imageData = tiff.toCanvas();
          ctx.drawImage(imageData, 0, 0, width, height);
          base64data = canvas.toDataURL('image/png');
        } else {
          // 处理其他格式图片
          const response = await fetch(image.imgUrl);
          if (!response.ok) {
            throw new Error(`Failed to load image: ${response.statusText}`);
          }
          const blob = await response.blob();
          base64data = await new Promise((resolve, reject) => {
            const reader = new FileReader();
            reader.onloadend = () => resolve(reader.result);
            reader.onerror = () => reject(new Error('Failed to convert to base64'));
            reader.readAsDataURL(blob);
          });
        }

        // 验证base64数据
        if (!base64data || !base64data.includes('base64,')) {
          throw new Error('Invalid base64 conversion result');
        }

        // 确保base64数据包含正确的MIME类型前缀
        const base64WithMime = base64data.startsWith('data:') 
          ? base64data 
          : `data:image/png;base64,${base64data.split(',')[1] || base64data}`;

        // 构建元数据对象，使用后端定义的字段名
        console.log('Original image data:', image);
        const metadata = {
          width: image.width,
          height: image.height,
          file_size: image.file_size,
          mime_type: image.mime_type,
          created_at: image.created_at,
          file_hash: image.file_hash,
          metadata: image.metadata
        };
        console.log('Constructed metadata:', metadata);

        this.$router.push({
          path: '/detail',
          query: {
            imgUrl: base64WithMime,
            imgUrlFortif: base64WithMime,
            experimentSetId: image.experiment_set_id,
            batchId: image.batch_id,
            experimentId: image.experiment_id,
            tx_hash: image.tx_hash,
            metadata: JSON.stringify(metadata)
          }
        });
      } catch (error) {
        console.error('处理图片失败:', error);
        message.error(error.message || '处理图片失败');
      } finally {
        // 重置图片状态
        if (index !== -1) {
          this.Data[index].processing = false;
        }
      }
    },

    toImageFilesTablePage() {
      const requiredParams = [
        'experiment_set_name',
        'experiment_batch_name',
        'experiment_name'
      ];
      const missingParams = requiredParams.filter(param => !this.$route.query[param]);
      if (missingParams.length > 0) {
        message.error('缺少必要的参数');
        return;
      }

      this.$router.push({
        path: '/MyData/ImageFilesTable',
        query: {
          experiment_set_name: this.$route.query.experiment_set_name,
          experiment_batch_name: this.$route.query.experiment_batch_name,
          experiment_name: this.$route.query.experiment_name,
        }
      });
    },
  },
});
</script>

<style scoped>
.scroll-container {
  max-width: 90vw;
  margin: auto;
  padding: 20px;
  max-height: 70vh;
  overflow-y: auto;
}

.image-container {
  position: relative;
  max-width: 90%;
  padding: 0 0 8px 10px;
  background: #fff;
  border-radius: 4px;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
  transition: transform 0.2s;
}

.image-container:hover {
  transform: translateY(-2px);
  box-shadow: 0 2px 6px rgba(0, 0, 0, 0.15);
}

.image-style {
  max-width: 100%;
  max-height: 100px;
  display: block;
  margin: auto;
  object-fit: contain;
}

/* Responsive adjustments */
@media (max-width: 768px) {
  .image-container .a-image {
    max-height: 150px;
  }
}

@media (max-width: 480px) {
  .image-container .a-image {
    max-height: 100px;
  }
}
</style>